/**
 * 简历管理API接口
 */
import { request } from '@/utils/request'

// 简历类型定义
export interface Resume {
  id: number
  student: number
  student_name: string
  resume_type: 'uploaded' | 'generated'
  uploaded_file?: string
  template?: number
  template_name?: string
  title: string
  status: 'draft' | 'in_progress' | 'submitted' | 'under_review' | 'approved' | 'rejected'
  current_step: number
  completion_rate: number
  reviewer?: number
  reviewer_name?: string
  review_date?: string
  review_comments?: string
  generated_file?: string
  generated_file_url?: string
  generated_file_name?: string
  generated_file_type?: string
  generated_at?: string
  // AI评估相关字段
  ai_evaluation_status: 'not_started' | 'in_progress' | 'completed' | 'failed'
  ai_evaluation_file?: string
  ai_evaluation_content?: string
  ai_evaluation_job_position?: string
  ai_evaluation_at?: string
  ai_evaluation_error?: string
  created_at: string
  updated_at: string
}

export interface ResumeTemplate {
  id: number
  name: string
  description: string
  template_file: string
  preview_image?: string
  is_active: boolean
  created_at: string
  updated_at: string
}

export interface BasicInfo {
  id?: number
  name: string
  gender: 'male' | 'female' | 'other'
  birth_date?: string
  phone: string
  email: string
  address?: string
  avatar?: string
  job_intention?: string
  expected_salary?: string
  work_location?: string
  created_at?: string
  updated_at?: string
}

export interface Education {
  id?: number
  school_name: string
  major: string
  degree: 'bachelor' | 'master' | 'doctor' | 'other'
  start_date: string
  end_date?: string
  is_current: boolean
  gpa?: string
  description?: string
  order: number
}

export interface Skill {
  id?: number
  name: string
  level: 'beginner' | 'intermediate' | 'advanced' | 'expert'
  description?: string
  order: number
}

export interface Project {
  id?: number
  name: string
  start_date: string
  end_date?: string
  is_current: boolean
  company_or_organization?: string
  overview: string
  role: string
  responsibilities: string
  problems_and_summary?: string
  // 保留原有字段以兼容
  description?: string
  technologies?: string
  achievements?: string
  url?: string
  order: number
}

export interface WorkExperience {
  id?: number
  company_name: string
  position_name: string
  start_date: string
  end_date?: string
  is_current: boolean
  job_responsibilities: string
  // 保留原有字段以兼容
  position?: string
  description?: string
  achievements?: string
  order: number
}

export interface Award {
  id?: number
  award_name: string
  award_level: 'school' | 'county' | 'city' | 'province' | 'national'
  certificate_photo?: string | File
  award_description?: string
  date_received: string
  // 保留原有字段以兼容
  name?: string
  issuer?: string
  description?: string
  certificate_file?: string
  order: number
}

export interface SelfIntroduction {
  id?: number
  content: string
  created_at?: string
  updated_at?: string
}

// 查询参数类型
export interface ResumeQueryParams {
  page?: number
  page_size?: number
  status?: string
  resume_type?: string
  student_id?: string | number
  student_name?: string
}

// 文件上传参数
export interface FileUploadParams {
  file: File
  title?: string
}

// 简历API
export const resumeApi = {
  // 获取简历列表
  getResumeList: (params?: ResumeQueryParams) => 
    request.get('/resume-management/resumes/', { params }),

  // 获取简历详情
  getResumeDetail: (id: number) => 
    request.get(`/resume-management/resumes/${id}/`),

  // 创建简历
  createResume: (data: Partial<Resume>) => 
    request.post('/resume-management/resumes/', data),

  // 更新简历
  updateResume: (id: number, data: Partial<Resume>) => 
    request.put(`/resume-management/resumes/${id}/`, data),

  // 删除简历
  deleteResume: (id: number) => 
    request.delete(`/resume-management/resumes/${id}/`),

  // 上传简历文件
  uploadResumeFile: (id: number, data: FormData) => 
    request.post(`/resume-management/resumes/${id}/upload_file/`, data, {
      headers: { 'Content-Type': 'multipart/form-data' }
    }),

  // 下载简历文件
  downloadResume: (id: number) => 
    request.get(`/resume-management/resumes/${id}/download/`),

  // 生成简历
  generateResume: (id: number, format: string = 'docx') =>
    request.post(`/resume-management/resumes/${id}/generate/`, { format }),

  // 提交简历
  submitResume: (id: number) =>
    request.post(`/resume-management/resumes/${id}/submit/`),

  // 更新完成度
  updateCompletion: (id: number) =>
    request.post(`/resume-management/resumes/${id}/update-completion/`),

  // 提交简历审核
  submitForReview: (id: number, data?: { submission_note?: string }) =>
    request.post(`/resume-management/resumes/${id}/submit-for-review/`, data || {}),

  // 提交AI评估
  submitAIEvaluation: (id: number, data: { job_id: number }) =>
    request.post(`/resume-management/resumes/${id}/ai_evaluation/`, data),

  // 获取AI评估状态
  getAIEvaluationStatus: (id: number) =>
    request.get(`/resume-management/resumes/${id}/ai_evaluation_status/`),

  // 获取AI评估结果内容
  getAIEvaluation: (id: number) =>
    request.get(`/resume-management/resumes/${id}/get_ai_evaluation/`),

  // 下载AI评估报告
  downloadAIEvaluation: (id: number) =>
    request.get(`/resume-management/resumes/${id}/download_ai_evaluation/`),

  // 审核简历
  reviewResume: (id: number, data: { result: 'approved' | 'rejected', comments?: string }) =>
    request.post(`/resume-management/resumes/${id}/review/`, data),

  // 新的简历审核相关API
  // 获取待审核简历列表（老师端）
  getPendingReviews: (params?: any) =>
    request.get('/resume-management/pending-reviews/', { params }),

  // 获取老师可访问的简历列表（包括已审批的）
  getTeacherResumeList: (params?: any) =>
    request.get('/resume-management/teacher/resumes/', { params }),

  // 审核简历（老师端）
  reviewResumeAction: (resumeId: number, data: { review_status: string; review_comments?: string }) =>
    request.post(`/resume-management/resumes/${resumeId}/review-action/`, data),

  // 获取简历历史版本
  getResumeVersions: (resumeId: number) =>
    request.get(`/resume-management/resumes/${resumeId}/versions/`),

  // 获取学生简历历史记录（老师端）
  getStudentResumeHistory: (studentId: number) =>
    request.get(`/resume-management/students/${studentId}/resume-history/`),

  // 获取简历文件信息（用于预览）
  getResumeFileInfo: (resumeId: number) =>
    request.get(`/resume-management/resumes/${resumeId}/file-info/`),

  // 管理员端API
  // 获取所有简历（管理员端）
  getAllResumes: (params?: any) =>
    request.get('/resume-management/admin/all-resumes/', { params }),

  // 获取审核统计信息（管理员端）
  getReviewStatistics: () =>
    request.get('/resume-management/admin/review-statistics/'),

  // 批量更新简历状态（管理员端）
  updateResumeStatus: (data: { resume_ids: number[]; status: string; comments?: string }) =>
    request.post('/resume-management/admin/resume-status-update/', data)
}

// 简历模板API
export const resumeTemplateApi = {
  // 获取模板列表
  getTemplateList: () =>
    request.get('/resume-management/templates/'),

  // 获取模板详情
  getTemplateDetail: (id: number) =>
    request.get(`/resume-management/templates/${id}/`),

  // 创建模板
  createTemplate: (data: FormData | Partial<ResumeTemplate>) =>
    request.post('/resume-management/templates/', data, {
      headers: data instanceof FormData ? { 'Content-Type': 'multipart/form-data' } : {}
    }),

  // 更新模板
  updateTemplate: (id: number, data: FormData | Partial<ResumeTemplate>) =>
    request.put(`/resume-management/templates/${id}/`, data, {
      headers: data instanceof FormData ? { 'Content-Type': 'multipart/form-data' } : {}
    }),

  // 删除模板
  deleteTemplate: (id: number) =>
    request.delete(`/resume-management/templates/${id}/`)
}

// 基本信息API
export const basicInfoApi = {
  // 获取基本信息
  getBasicInfo: (resumeId: number) => 
    request.get(`/resume-management/resumes/${resumeId}/basic-info/`),

  // 创建/更新基本信息
  saveBasicInfo: (resumeId: number, data: BasicInfo | FormData) =>
    request.post(`/resume-management/resumes/${resumeId}/basic-info/`, data),

  // 更新基本信息
  updateBasicInfo: (resumeId: number, id: number, data: BasicInfo | FormData) =>
    request.put(`/resume-management/resumes/${resumeId}/basic-info/${id}/`, data)
}

// 教育背景API
export const educationApi = {
  // 获取教育背景列表
  getEducationList: (resumeId: number) => 
    request.get(`/resume-management/resumes/${resumeId}/education/`),

  // 创建教育背景
  createEducation: (resumeId: number, data: Education) => 
    request.post(`/resume-management/resumes/${resumeId}/education/`, data),

  // 更新教育背景
  updateEducation: (resumeId: number, id: number, data: Education) => 
    request.put(`/resume-management/resumes/${resumeId}/education/${id}/`, data),

  // 删除教育背景
  deleteEducation: (resumeId: number, id: number) => 
    request.delete(`/resume-management/resumes/${resumeId}/education/${id}/`)
}

// 技能API
export const skillApi = {
  // 获取技能列表
  getSkillList: (resumeId: number) => 
    request.get(`/resume-management/resumes/${resumeId}/skills/`),

  // 创建技能
  createSkill: (resumeId: number, data: Skill) => 
    request.post(`/resume-management/resumes/${resumeId}/skills/`, data),

  // 更新技能
  updateSkill: (resumeId: number, id: number, data: Skill) => 
    request.put(`/resume-management/resumes/${resumeId}/skills/${id}/`, data),

  // 删除技能
  deleteSkill: (resumeId: number, id: number) => 
    request.delete(`/resume-management/resumes/${resumeId}/skills/${id}/`)
}

// 项目经验API
export const projectApi = {
  // 获取项目列表
  getProjectList: (resumeId: number) => 
    request.get(`/resume-management/resumes/${resumeId}/projects/`),

  // 创建项目
  createProject: (resumeId: number, data: Project) => 
    request.post(`/resume-management/resumes/${resumeId}/projects/`, data),

  // 更新项目
  updateProject: (resumeId: number, id: number, data: Project) => 
    request.put(`/resume-management/resumes/${resumeId}/projects/${id}/`, data),

  // 删除项目
  deleteProject: (resumeId: number, id: number) => 
    request.delete(`/resume-management/resumes/${resumeId}/projects/${id}/`)
}

// 工作经验API
export const workExperienceApi = {
  // 获取工作经验列表
  getWorkExperienceList: (resumeId: number) => 
    request.get(`/resume-management/resumes/${resumeId}/work-experience/`),

  // 创建工作经验
  createWorkExperience: (resumeId: number, data: WorkExperience) => 
    request.post(`/resume-management/resumes/${resumeId}/work-experience/`, data),

  // 更新工作经验
  updateWorkExperience: (resumeId: number, id: number, data: WorkExperience) => 
    request.put(`/resume-management/resumes/${resumeId}/work-experience/${id}/`, data),

  // 删除工作经验
  deleteWorkExperience: (resumeId: number, id: number) => 
    request.delete(`/resume-management/resumes/${resumeId}/work-experience/${id}/`)
}

// 获奖经历API
export const awardApi = {
  // 获取获奖列表
  getAwardList: (resumeId: number) => 
    request.get(`/resume-management/resumes/${resumeId}/awards/`),

  // 创建获奖记录
  createAward: (resumeId: number, data: Award | FormData) =>
    request.post(`/resume-management/resumes/${resumeId}/awards/`, data, {
      headers: data instanceof FormData ? { 'Content-Type': 'multipart/form-data' } : {}
    }),

  // 更新获奖记录
  updateAward: (resumeId: number, id: number, data: Award | FormData) =>
    request.put(`/resume-management/resumes/${resumeId}/awards/${id}/`, data, {
      headers: data instanceof FormData ? { 'Content-Type': 'multipart/form-data' } : {}
    }),

  // 删除获奖记录
  deleteAward: (resumeId: number, id: number) => 
    request.delete(`/resume-management/resumes/${resumeId}/awards/${id}/`)
}

// 自我介绍API
export const selfIntroductionApi = {
  // 获取自我介绍
  getSelfIntroduction: (resumeId: number) => 
    request.get(`/resume-management/resumes/${resumeId}/self-introduction/`),

  // 创建/更新自我介绍
  saveSelfIntroduction: (resumeId: number, data: SelfIntroduction) => 
    request.post(`/resume-management/resumes/${resumeId}/self-introduction/`, data),

  // 更新自我介绍
  updateSelfIntroduction: (resumeId: number, id: number, data: SelfIntroduction) =>
    request.put(`/resume-management/resumes/${resumeId}/self-introduction/${id}/`, data),

  // 简历审核相关API
  // 提交简历审核
  submitForReview: (resumeId: number, data: { submission_note?: string }) =>
    request.post(`/resume-management/resumes/${resumeId}/submit-for-review/`, data),

  // 获取待审核简历列表（老师端）
  getPendingReviews: (params?: any) =>
    request.get('/resume-management/pending-reviews/', { params }),

  // 审核简历（老师端）
  reviewResume: (resumeId: number, data: { review_status: string; review_comments?: string }) =>
    request.post(`/resume-management/resumes/${resumeId}/review-action/`, data),

  // 获取简历历史版本
  getResumeVersions: (resumeId: number) =>
    request.get(`/resume-management/resumes/${resumeId}/versions/`),

  // 获取学生简历历史记录（老师端）
  getStudentResumeHistory: (studentId: number) =>
    request.get(`/resume-management/students/${studentId}/resume-history/`)
}

// 常量定义
export const RESUME_STATUS_OPTIONS = [
  { value: 'draft', label: '草稿' },
  { value: 'in_progress', label: '制作中' },
  { value: 'pending_review', label: '待审核' },
  { value: 'under_review', label: '审核中' },
  { value: 'approved', label: '已通过' },
  { value: 'rejected', label: '未通过' },
  { value: 'needs_revision', label: '待修改' }
]

export const DEGREE_OPTIONS = [
  { value: 'bachelor', label: '本科' },
  { value: 'master', label: '硕士' },
  { value: 'doctor', label: '博士' },
  { value: 'other', label: '其他' }
]

export const SKILL_LEVEL_OPTIONS = [
  { value: 'beginner', label: '初级' },
  { value: 'intermediate', label: '中级' },
  { value: 'advanced', label: '高级' },
  { value: 'expert', label: '专家' }
]

export const GENDER_OPTIONS = [
  { value: 'male', label: '男' },
  { value: 'female', label: '女' },
  { value: 'other', label: '其他' }
]

// 状态颜色映射
export const STATUS_COLOR_MAP = {
  'draft': 'info',
  'in_progress': 'warning',
  'pending_review': 'primary',
  'under_review': 'warning',
  'approved': 'success',
  'rejected': 'danger',
  'needs_revision': 'warning'
} as const

// 获取状态标签
export const getStatusLabel = (status: string): string => {
  const option = RESUME_STATUS_OPTIONS.find(s => s.value === status)
  return option ? option.label : status
}

// 获取状态颜色
export const getStatusColor = (status: string): 'primary' | 'success' | 'warning' | 'info' | 'danger' => {
  return (STATUS_COLOR_MAP[status as keyof typeof STATUS_COLOR_MAP] || 'info') as 'primary' | 'success' | 'warning' | 'info' | 'danger'
}
